package cn.shen.edit.service.imp;

import cn.shen.edit.common.WebResult;
import cn.shen.edit.common.WebResultUtil;
import cn.shen.edit.entity.Detail;
import cn.shen.edit.entity.Wallet;
import cn.shen.edit.mapper.DetailMapper;
import cn.shen.edit.mapper.WalletMapper;
import cn.shen.edit.service.WalletService;
import cn.shen.edit.vo.DetailVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
public class WalletServiceImp implements WalletService {

    @Autowired
    private WalletMapper walletMapper;

    @Autowired
    private DetailMapper detailMapper;

    @Override
    @Transactional
    public WebResult consumption(Long userId, Long amount) {
        Wallet wallet = walletMapper.selectById(userId);
        if (wallet.getBalance()-amount>=0){
            wallet.setBalance(wallet.getBalance()-amount);
            walletMapper.update(wallet,new LambdaQueryWrapper<Wallet>().eq(Wallet::getUserId,userId));
            log.info("消费成功");
            detailMapper.insert(Detail.builder()
                    .userId(userId)
                    .amount(amount)
                    .upOrDown(1)
                    .build());
            log.info("消费日志写入成功");
        }else {
            return WebResultUtil.genErrorResult("余额不足");
        }
        return WebResultUtil.genSuccessResult("成功消费");
    }

    @Override
    @Transactional
    public WebResult refund(Long userId, Long amount) {
        Wallet wallet = walletMapper.selectById(userId);
        wallet.setBalance(wallet.getBalance()+amount);
        walletMapper.update(wallet,new LambdaQueryWrapper<Wallet>().eq(Wallet::getUserId,userId));
        log.info("退款成功");
        detailMapper.insert(Detail.builder()
                .userId(userId)
                .amount(amount)
                .upOrDown(0)
                .build());
        log.info("退款日志写入成功");
        return WebResultUtil.genSuccessResult("成功消费");
    }

    public WebResult detail(DetailVo vo){
        Page<Detail> detailPage = PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<Detail> detailList = detailMapper.selectList(new LambdaQueryWrapper<Detail>().eq(Detail::getUserId, vo.getUserId()));
        PageInfo<Detail> detailPageInfo = detailPage.toPageInfo();
        detailPageInfo.setList(detailList);
        log.info("查询完毕");
        log.info("当前查询页码: {},当前查询每页数量: {}",vo.getPageNum(),vo.getPageSize());
        return WebResultUtil.genSuccessResult(detailPageInfo);
    }


}
